package com.gopay.bis.cib.ebank.transformer;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * 兴业订单查询通讯类
 * 
 * @CibQueryTransformer.java
 * @author zhengxue
 * @2014-11-27 下午4:03:15 www.gopay.com.cn Inc.All rights reserved.
 */
public class CibQueryTransformer {
    private static DefaultHttpClient client;

    /**
     * 访问https的网站
     * 
     * @param httpclient
     */
    private static void enableSSL(DefaultHttpClient httpclient) {
        // 调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写验证方法，取消检测ssl
     */
    private static TrustManager truseAllManager = new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    };

    /**
     * 
     * @param url
     * @param obj
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public Object submit(String url, Object obj) throws Exception {
        String result = "";
        synchronized (this){
            if (client == null) {
                // Create HttpClient Object
                client = new DefaultHttpClient();
                enableSSL(client);
            }
        }
        client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

        HttpPost method = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000).build();
        method.setHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        method.setHeader(HTTP.USER_AGENT, "Rich Powered/1.0");
        method.setConfig(requestConfig);

        Map<String, String> paraMap = (Map<String, String>) obj;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        for (Iterator<String> iter = paraMap.keySet().iterator(); iter.hasNext();) {
            String key = iter.next();
            String value = "";
            if (paraMap.get(key) != null) {
                value = paraMap.get(key);
            }

            nvps.add(new BasicNameValuePair(key, value));
        }
        method.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

        synchronized (client) {
            HttpResponse response = client.execute(method);
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity, "UTF-8");
            EntityUtils.consume(responseEntity);
            method.abort();
        }
        return result;
    }

}